Delegate (CLI)
   HOME

TheInfoList



OR:

A delegate is a form of
type-safe In computer science, type safety and type soundness are the extent to which a programming language discourages or prevents type errors. Type safety is sometimes alternatively considered to be a property of facilities of a computer language; that is ...
function pointer A function pointer, also called a subroutine pointer or procedure pointer, is a pointer that points to a function. As opposed to referencing a data value, a function pointer points to executable code within memory. Dereferencing the function poi ...
used by the Common Language Infrastructure (CLI). Delegates specify a
method Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to: *Scien ...
to call and optionally an
object Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an ...
to call the method on. Delegates are used, among other things, to implement callbacks and event listeners. A delegate object encapsulates a reference to a method. The delegate object can then be passed to code that can call the referenced method, without having to know at compile time which method will be invoked. A multicast delegate is a delegate that points to several methods.
Multicast In computer networking, multicast is group communication where data transmission is addressed to a group of destination computers simultaneously. Multicast can be one-to-many or many-to-many distribution. Multicast should not be confused with ...
delegation is a mechanism that provides functionality to execute more than one method. There is a list of delegates maintained internally, and when the multicast delegate is invoked, the list of delegates is executed. In C#, delegates are often used to implement callbacks in event driven programming. For example, a delegate may be used to indicate which method should be called when the user clicks on some button. Delegates allow the programmer to notify several methods that an event has occurred. Wikibooks:C Sharp Programming/Delegates and Events


C# code example

Code to declare a delegate type, named SendMessageDelegate, which takes a Message as a parameter and returns void: delegate void SendMessageDelegate(Message message); Code to define a method that takes an instantiated delegate as its argument: void SendMessage(SendMessageDelegate sendMessageDelegateReference) The implemented method that runs when the delegate is called: void HandleSendMessage(Message message) Code to call the SendMessage method, passing an instantiated delegate as an argument: SendMessage(new SendMessageDelegate(HandleSendMessage));


Delegates (C#)

delegate void Notifier(string sender); // Normal method signature with the keyword delegate Notifier greetMe; // Delegate variable void HowAreYou(string sender) greetMe = new Notifier(HowAreYou); A delegate variable calls the associated method and is called as follows: greetMe("Anton"); // Calls HowAreYou("Anton") and prints "How are you, Anton?" Delegate variables are
first-class object In programming language design, a first-class citizen (also type, object, entity, or value) in a given programming language is an entity which supports all the operations generally available to other entities. These operations typically include ...
s of the form and can be assigned to any matching method, or to the value . They store a method and its receiver without any parameters: new DelegateType(funnyObj.HowAreYou); The object can be and omitted. If the method is , it should not be the object (also called an instance in other languages), but the class itself. It should not be , but could be , or . To call a method with a delegate successfully, the method signature has to match the with the same number of parameters of the same kind (, , ) with the same type (including return type).


Multicast delegates (C#)

A delegate variable can hold multiple values at the same time: void HowAreYou(string sender) void HowAreYouToday(string sender) Notifier greetMe; greetMe = HowAreYou; greetMe += HowAreYouToday; greetMe("Leonardo"); // "How are you, Leonardo?" // "How are you today, Leonardo?" greetMe -= HowAreYou; greetMe("Pereira"); // "How are you today, Pereira?" If the multicast delegate is a function or has no parameter, the parameter of the last call is returned.


Technical implementation details

Although internal
implementation Implementation is the realization of an application, or execution of a plan, idea, model, design, specification, standard, algorithm, or policy. Industry-specific definitions Computer science In computer science, an implementation is a real ...
s may vary, delegate instances can be thought of as a
tuple In mathematics, a tuple is a finite ordered list (sequence) of elements. An -tuple is a sequence (or ordered list) of elements, where is a non-negative integer. There is only one 0-tuple, referred to as ''the empty tuple''. An -tuple is defi ...
of an
object Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an ...
and a
method Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to: *Scien ...
pointer and a
reference Reference is a relationship between objects in which one object designates, or acts as a means by which to connect to or link to, another object. The first object in this relation is said to ''refer to'' the second object. It is called a ''name'' ...
(possibly null) to another delegate. Hence a reference to one delegate is possibly a reference to multiple delegates. When the first delegate has finished, if its chain reference is not null, the next will be invoked, and so on until the list is complete. This pattern allows an
event Event may refer to: Gatherings of people * Ceremony, an event of ritual significance, performed on a special occasion * Convention (meeting), a gathering of individuals engaged in some common interest * Event management, the organization of e ...
to have overhead scaling easily from that of a single reference up to dispatch to a list of delegates, and is widely used in the CLI.


Performance

Performance of delegates used to be much slower than a virtual or
interface Interface or interfacing may refer to: Academic journals * ''Interface'' (journal), by the Electrochemical Society * '' Interface, Journal of Applied Linguistics'', now merged with ''ITL International Journal of Applied Linguistics'' * '' Int ...
method call (6 to 8 times slower in Microsoft's 2003 benchmarks), but, since the .NET 2.0
CLR CLR may refer to: * Calcium Lime Rust, a household cleaning-product * California Law Review, a publication by the UC Berkeley School of Law * Tube_bending, Centerline Radius, a term in the tubing industry used to describe the radius of a bend * Cen ...
in 2005, it is about the same as interface calls. This means there is a small added overhead compared to direct method invocations. There are very stringent rules on the construction of delegate classes. These rules permit optimizing compilers a great deal of leeway when optimizing delegates while ensuring type safety.


See also

*
Continuation In computer science, a continuation is an abstract representation of the control state of a computer program. A continuation implements ( reifies) the program control state, i.e. the continuation is a data structure that represents the computati ...
*
Delegation pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows object composition to achieve the same code reuse as inheritance. In delegation, an object handles a request by delegating to a second object (the ''de ...
*
Delegation (programming) In computing or computer programming, delegation refers generally to one entity passing something to another entity,Barry Wilkinson, ''Grid Computing: Techniques and Applications'' (2009), p. 164, . and narrowly to various specific forms of relat ...
*
Hooking In computer programming, the term hooking covers a range of techniques used to alter or augment the behaviour of an operating system, of applications, or of other software components by intercepting function calls or messages or events passed ...


References


External links


MSDN documentation for Delegates



Microsoft answer to Sun
{{DEFAULTSORT:Delegate Common Language Infrastructure Subroutines